package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import com.example.xcService.pojo.tool.StringTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 峰助手接口
 * **/
@Slf4j
public class Plugin_ECARD_P011 implements ChannelService {
    public ChannelResult QueryBalance(JSONObject apiConfig){
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }
    public  ChannelResult Submit(JSONObject apiConfig, Map<String,Object> data){

        try {
            String timestamp=String.valueOf(System.currentTimeMillis());

            JSONObject dataConfig= JSONObject.parseObject(JSONObject.toJSONString(data));

            Map<String,String> shipInfo=new HashMap<>();
            shipInfo.put("account",dataConfig.getString("AccountVal"));


            Map dataParams = new LinkedHashMap<String, String>();
            dataParams.put("channelId",  apiConfig.getString("USERID"));
            dataParams.put("appKey", apiConfig.getString("appKey"));
            dataParams.put("timestamp", timestamp);
            dataParams.put("srvType","recharge");
            dataParams.put("orderId", dataConfig.getString("ChannelOrderCode"));
            dataParams.put("skuCode", dataConfig.getString("SUPProductId"));
            dataParams.put("num", "1");
            dataParams.put("shipInfo", JSONObject.toJSONString(shipInfo));
            dataParams.put("returl","http://cz.llczy.com/ApiChannel/v3/ECARD/C0111");

            String str = getSignStr(dataParams);


            String sign=DigestUtils.sha1Hex(apiConfig.getString("SecretKey")+str + apiConfig.getString("SecretKey"));
            dataParams.put("sign", sign.toUpperCase());



            String url=apiConfig.getString("SubmitURL");

            String responseContent = HttpTool.sendGet(url, dataParams);
            JSONObject retobj = JSONObject.parseObject(responseContent);

            String code = retobj.getString("retcode");
            String msg = retobj.getString("msg");
            if (code.equals("0")) {
                return ChannelResult.IN_PROCESS();
            }
            else if (code.equals("1")){
                return ChannelResult.success("充值成功");
            }
            else if (code.equals("9")){
                return ChannelResult.FAILED("充值失败");
            }
            else {
                return ChannelResult.FAILED(code+","+msg);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            log.error("峰助手提交订单接口错误：",ex);
            return  ChannelResult.error("峰助手提交订单接口错误");
        }
    }

    public  ChannelResult Query(JSONObject apiConfig,Map<String,Object> data) {
        try {




            JSONObject dataConfig= JSONObject.parseObject(JSONObject.toJSONString(data));

            String timestamp=String.valueOf(System.currentTimeMillis());

            Map<String,String> shipInfo=new HashMap<>();
            shipInfo.put("account",dataConfig.getString("AccountVal"));


            Map dataParams = new LinkedHashMap<String, String>();
            dataParams.put("channelId",  apiConfig.getString("USERID"));
            dataParams.put("appKey", apiConfig.getString("appKey"));
            dataParams.put("timestamp", timestamp);
            dataParams.put("orderId", dataConfig.getString("ChannelOrderCode"));

            String str = getSignStr(dataParams);


            String sign= DigestUtils.sha1Hex(apiConfig.getString("SecretKey")+str + apiConfig.getString("SecretKey"));
            dataParams.put("sign", sign.toUpperCase());


            String url = apiConfig.getString("QueryURL");
            String responseContent = HttpTool.sendGet(url, dataParams);
            JSONObject retobj = JSONObject.parseObject(responseContent);

            String code = retobj.getString("retcode");
            String msg = retobj.getString("msg");
            if (code.equals("0")) {
                return ChannelResult.IN_PROCESS();
            }
            else if (code.equals("1")){
                return ChannelResult.success("充值成功");
            }
            else if (code.equals("9")){
                return ChannelResult.FAILED("充值失败");
            }
            else {
                return ChannelResult.error(code+","+msg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("峰助手查询订单接口错误：", ex);
            return ChannelResult.error("蜂助手查询订单接口错误");
        }
    }


    public  ChannelResult Notify(JSONObject apiConfig,Map<String,Object> data){
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");

    }

    /**
     * 生成签名
     *
     * @param map
     * @return
     */
    public static String getSignStr(Map<String, String> map) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key +"="+ val);
                    }
                }
            }
            result = sb.toString();
        } catch (Exception e) {
            log.error("获取签名明文出错：", e);
            return null;
        }
        return result;
    }
}
